package com.dd.admin.business.file.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dd.admin.common.exception.ApiException;
import com.dd.admin.common.model.PageFactory;
import com.dd.admin.business.file.entity.File;
import com.dd.admin.business.file.mapper.FileMapper;
import com.dd.admin.business.file.service.FileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.admin.common.utils.FileUtil;
import com.dd.admin.common.utils.ToolUtil;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.tomcat.jni.FileInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.dd.admin.business.file.domain.FileVo;
import com.dd.admin.business.file.domain.FileDto;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.util.List;

/**
 * <p>
 * 文件 服务实现类
 * </p>
 *
 * @author 727869402@qq.com
 * @since 2024-05-23
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements FileService {

    @Value("${dd.uploadPath}")
    private String uploadPath;

    @Override
    public IPage<FileVo> selectFilePage(FileDto fileDto) {
        Page page = PageFactory.defaultPage();
        return baseMapper.selectFilePage(page,fileDto);
    }

    @Override
    public List<FileVo> selectFileList(FileDto fileDto) {
        return baseMapper.selectFileList(fileDto);
    }

    @Override
    public File selectFileByFileId(String fileId) {
        return getById(fileId);
    }

    public String getSysUploadPath(){
        java.io.File filepath = new java.io.File(uploadPath);
        //该目录不存在 则创建
        if (!filepath.exists()) {
            boolean mkdirs = filepath.mkdirs();
        }
        return uploadPath;
    }


    @Override
    public FileVo uploadFile(MultipartFile file, String fileSavePath) {



        //需要返回的对象
        FileVo fileVo = new FileVo();

        //生成文件的唯一id
        String fileId = IdWorker.get32UUID();
        fileVo.setFileId(fileId);

        //获取文件后缀
        String fileSuffix = ToolUtil.getFileSuffix(file.getOriginalFilename());
        fileVo.setFileSuffix(fileSuffix);

        //获取文件原始名称
        String originalFilename = file.getOriginalFilename();
        fileVo.setOriginalFilename(originalFilename);

        //生成文件的最终名称
        String finalName = fileId + "." + ToolUtil.getFileSuffix(originalFilename);
        fileVo.setFinalName(finalName);
        fileVo.setFileSavePath(fileSavePath + finalName);

        String sysUploadPath = getSysUploadPath();

        String newFileSavePath = "";

        //判断有没有结尾符,没有得加上
        if (!fileSavePath.endsWith(java.io.File.separator)) {
            newFileSavePath = fileSavePath + java.io.File.separator;
        }

        try {
            java.io.File filepath = new java.io.File(sysUploadPath + newFileSavePath );
            //该目录不存在 则创建
            if (!filepath.exists()) {
                boolean mkdirs = filepath.mkdirs();
            }
            System.out.println(filepath.getAbsolutePath());
            System.out.println(filepath.getPath());

            java.io.File newFile = null;
            try {
            // 先尝试压缩并保存图片
                Thumbnails.of(file.getInputStream()).scale(1)
                        .outputQuality(0.25f)
                        .toFile(sysUploadPath + newFileSavePath + finalName);
                newFile = new java.io.File(sysUploadPath + newFileSavePath + finalName);
            } catch (IOException e) {
                //保存文件到指定目录
                 newFile = new java.io.File(sysUploadPath + newFileSavePath + finalName);
                file.transferTo(newFile);
            }


            File fileInfo = new File();
            //保存文件信息
            fileInfo.setFileId(fileId);
            fileInfo.setFileName(originalFilename);
            fileInfo.setFileSuffix(fileSuffix);

            fileInfo.setFilePath("/upload/" + fileSavePath + "/" + finalName);

            fileVo.setFileSavePath(fileInfo.getFilePath());
            fileInfo.setFinalName(finalName);

            //计算文件大小kb
            long kb = new BigDecimal(file.getSize())
                    .divide(BigDecimal.valueOf(1024))
                    .setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
            fileInfo.setFileSizeKb(kb);
            fileInfo.setFileSysPath(newFile.getAbsolutePath());

            save(fileInfo);
        } catch (Exception e) {
            log.error("上传文件错误！", e);
            throw new ApiException("上传文件错误！");
        }
        return fileVo;
    }


    @Override
    public String getFileAuthUrl(String fileId) {
        File file = getById(fileId);
        if(file!=null){
            return file.getFilePath();
        }
        return "";
    }


}
